<template>
    <el-card :body-style="{paddingTop: '12px'}">
      <div class="container" ref="target"></div>
    </el-card>
  </template>

<script setup>
import { onMounted, ref } from 'vue'
import * as echarts from 'echarts'
import { useI18n } from 'vue-i18n'
import { getChartTimeAmount } from '@/api/chart'
import { watchSwitchLang } from '@/utils/i18n'
import emitter from '@/utils/eventHub'
const data = ref([])
const getData = async () => {
  const { result } = await getChartTimeAmount()
  data.value = result
  renderChart()
}

getData()

const i18n = useI18n()

const target = ref(null)
let mChart = null
onMounted(() => {
  mChart = echarts.init(target.value)
})

const renderChart = () => {
  const options = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: [
        `${i18n.t('msg.chart.income')} (${i18n.t('msg.chart.unit')})`,
        `${i18n.t('msg.chart.expend')} (${i18n.t('msg.chart.unit')})`,
        `${i18n.t('msg.chart.balance')} (${i18n.t('msg.chart.unit')})`
      ],
      right: 0
    },
    grid: {
      top: 28,
      bottom: 0,
      left: 0,
      right: 0,
      containLabel: true
    },
    xAxis: [
      {
        type: 'value'
      }
    ],
    yAxis: [
      {
        type: 'category',
        axisTick: {
          show: false
        },
        data: data.value.map(item => item.timeStr),
        inverse: true
      }
    ],
    series: [
      {
        name: `${i18n.t('msg.chart.income')} (${i18n.t('msg.chart.unit')})`,
        type: 'bar',
        stack: 'Total',
        label: {
          show: true,
          position: 'right'
        },
        color: '#6DC473',
        emphasis: {
          focus: 'series'
        },
        data: data.value.map(item => item.income)
      },
      {
        name: `${i18n.t('msg.chart.expend')} (${i18n.t('msg.chart.unit')})`,
        type: 'bar',
        stack: 'Total',
        label: {
          show: true,
          position: 'right'
        },
        color: '#ed7470',
        emphasis: {
          focus: 'series'
        },
        data: data.value.map(item => item.expense)
      },
      {
        name: `${i18n.t('msg.chart.balance')} (${i18n.t('msg.chart.unit')})`,
        type: 'bar',
        label: {
          show: true,
          position: 'inside'
        },
        color: '#83c0df',
        emphasis: {
          focus: 'series'
        },
        data: data.value.map(item => item.balance)
      }
    ]
  }

  mChart.setOption(options)
}

watchSwitchLang(renderChart)

emitter.on('calendarChange', val => {
  getData(val)
})

</script>

  <style lang="scss" scoped>
  .container {
    height: 403px;
  }
  </style>
